//角色控制器
import { _decorator, Component, RigidBody, SkeletalAnimation, Vec3, Node, tween, Label } from 'cc';
import { RoadManager } from '../managers/RoadManager';
import { obstacleManager } from '../managers/ObstacleManager';
import { PlayerManager } from '../managers/PlayerManager';
const { ccclass, property } = _decorator;

@ccclass('PlayerController')
export class PlayerController extends Component {
    @property({
        tooltip: "转换赛道的Force值"
    })
    private switchPlaces = 100;

    @property({
        tooltip: "跑步动画初始速度值"
    })
    private animSpeed: number = 0.8;

    @property({
        tooltip: "跑步动画加速值"
    })
    private addAnimSpeed: number = 0.001;

    @property({
        tooltip: "跳跃高度"
    })
    jumpForce: number = 130;

    private recoveryCallback: Function = null;
    private obstaclemanager: obstacleManager
    private playerManager: PlayerManager;
    private roadManager: RoadManager;
    private rigidBody: RigidBody;
    private jumpHight: number;
    public savePlayerVec3: Vec3;
    jumpBool

    @property(Label)
    lable: Label;
    downBool: boolean;

    start() {
        this.downBool = true;
        //初始化
        if (!this.rigidBody) {
            this.rigidBody = this.getComponent(RigidBody);
        }
        this.roadManager = RoadManager.getInstance();
        this.playerManager = PlayerManager.getInstance();
        this.obstaclemanager = obstacleManager.getInstance();
        this.playerManager.setPlayerControllerClass = this;


        let that = this;
        this.runStart();
        //循环加速，并持续增加动画播放速度
        let time = function () {
            setTimeout(() => {
                that.playerManager.ForceAdd1();
                that.animSpeed += that.addAnimSpeed;
                if (that.rigidBody && !that.roadManager.isMoving && !that.playerManager.jump) {
                    that.runStart();
                }
                time();
            }, 3000);
        }
        time();

        // 确保重力影响正常
        this.rigidBody.useGravity = true;
        // 确保角色可以在 Y 轴方向自由移动
        this.rigidBody.linearFactor = new Vec3(1, 1, 1);  // X、Y、Z 轴上都允许移动
    }

    //向前推加速度-开跑
    runStart() {
        this.LinearVelocity()

        const skeletalAnimation = this.getComponent(SkeletalAnimation);
        const animState = skeletalAnimation.getState('Take 001');
        animState.speed = this.animSpeed;
    }

    update(dt) {

        //跳跃临界点
        if (this.node.position.y > this.jumpHight + 15) {
            this.stopMovement();
            let forceVec = new Vec3(0, -50, 0);
            this.rigidBody.applyImpulse(forceVec, this.rigidBody.node.worldPosition);
        }

        //是否更改动画判断
        if (this.jumpBool !== this.playerManager.jump) {
            this.jumpBool = this.playerManager.jump;
            this.playerState();
        }

        //掉落死亡判断
        if (this.node.position.y < -8) {
            this.playerManager.GameOverFunction();
        }
    }


    //向左按钮
    addLeftMovement() {
        this.turnPackaged(this.roadManager.leftR, this.switchPlaces);
    }

    //向右按钮
    addRightMovement() {
        this.turnPackaged(this.roadManager.rightR, -this.switchPlaces);
    }

    //向左右施加力
    turnPackaged(e, m) {
        if (!e || e.position == null || this.roadManager.isMoving) return;
        this.roadManager.setIsMoving(true);
        this.rigidBody.angularFactor = new Vec3(0, 0, 0);
        this.savePlayerVec3 = this.node.getWorldPosition();

        this.roadManager.saveName(e);

        this.applyImpulseToRigidbody(m);

    }

    //线性加速度
    LinearVelocity(e = new Vec3(0, 0, this.playerManager.Force)) {
        let currentVelocity = new Vec3();
        this.rigidBody.getLinearVelocity(currentVelocity);
        currentVelocity = e;
        this.rigidBody.setLinearVelocity(currentVelocity);
    }

    //瞬间加速度
    applyImpulseToRigidbody(m) {
        let force = new Vec3(m, 0, 0);
        this.rigidBody.applyImpulse(force);
    }

    //持续加速度
    applyForceToRigidbody(m) {
        let force = new Vec3(m, 0, 0);
        this.rigidBody.applyForce(force);
    }


    //碰撞后的速度恢复，在3秒内恢复到原来的速度
    setTouchForce() {

    }

    //跳跃函数
    jumpMovement() {
        if (this.playerManager.jump) return;
        if (this.recoveryCallback) {
            this.unschedule(this.recoveryCallback);
        }
        this.recovery(0.1);
        this.playerManager.jump = true;
        this.jumpHight = this.node.position.y;

        this.rigidBody.angularFactor = new Vec3(0, 0, 0);
        this.rigidBody.linearDamping = 0;  // 保持阻尼为 0 或很小

        let Impulse = new Vec3(0, this.jumpForce, 20);
        this.rigidBody.applyImpulse(Impulse, this.node.worldPosition);

    }

    //是否播放跑步动画
    playerState() {
        if (this.playerManager.jump) {
            this.getComponent(SkeletalAnimation).stop();
        } else {
            this.getComponent(SkeletalAnimation).play();
        }

    }

    // 清除物体的速度和角速度，停止运动
    stopMovement() {
        this.rigidBody.clearVelocity();
        this.rigidBody.getAngularVelocity(new Vec3(0, 0, 0));
        this.LinearVelocity()
    }

    //蹲下后执行的函数-缩小角色后变回去
    downForce() {
        if (!this.downBool) return;
        this.downBool = false;
        // 保存匿名函数的引用
        this.recoveryCallback = () => {
            this.recovery(0.5);
        };
        console.log(this.node.getPosition().y);
        this.lable.string = `角色高度${this.node.getPosition().y}`
        if (this.node.getPosition().y > 4.5) {
            let Impulse = new Vec3(0, -280, 150);
            this.rigidBody.applyImpulse(Impulse, this.node.worldPosition);
        }
        tween(this.node)
            .to(0.2, { scale: new Vec3(1, 0.3, 1) }, { easing: 'sineOut' })  // 在0.5秒内缩小
            .start();
        this.scheduleOnce(this.recoveryCallback, 1.5);
    }

    //恢复原来的大小
    recovery(e) {
        tween(this.node)
            .to(e, { scale: new Vec3(1, 1, 1) }, { easing: 'sineOut' })  // 在0.5秒内恢复
            .start();
        setTimeout(() => {

            this.downBool = true;
        }, 800);
    }
}
